package com.yida.auth.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.yida.auth.form.LoginBody;
import com.yida.auth.service.BasicDataService;
import com.yida.auth.service.SysOutsideLoginService;
import com.yida.common.core.domain.R;
import com.yida.common.core.utils.sign.RsaUtils;
import com.yida.common.security.service.OutsideTokenService;
import com.yida.system.api.model.LoginUser;

/**
 * token 控制
 * 
 * @author yida
 */
@RestController
public class OutsideTokenController {

    @Autowired
    private OutsideTokenService outsideTokenService;

    @Autowired
    private SysOutsideLoginService sysOutsideLoginService;

    @Autowired
    public BasicDataService basicDataService;

    // @PostMapping("login")
    // public R<?> login(@RequestBody LoginBody form) throws Exception {
    // LoginUser userInfo = null;
    // String passwordInfo = RsaUtils.decryptByPrivateKey(form.getPassword());
    // if (!"admin".equals(form.getUsername())) {
    // // 获取手机校验开关
    // String codeEnabled = basicDataService.getPhoneCodeEnabled();
    // if ("true".equals(codeEnabled)) {
    // userInfo = sysLoginService.login(form.getUsername(), passwordInfo, form.getPhonenumber(),form.getSmsCode());
    // }else {
    // userInfo = sysLoginService.login(form.getUsername(), passwordInfo);
    // }
    // }
    // if (userInfo == null && "admin".equals(form.getUsername())) {
    // userInfo = sysLoginService.login(form.getUsername(), passwordInfo);
    // }
    //
    // if (userInfo == null) {
    // return R.fail("无效登陆操作!");
    // }
    //
    // // 获取登录token
    // return R.ok(tokenService.createToken(userInfo));
    // }

    @PostMapping("outsideLogin")
    public R<?> login(@RequestBody LoginBody form) throws Exception {
        LoginUser userInfo = null;
        String passwordInfo = RsaUtils.decryptByPrivateKey(form.getPassword());
        // 获取手机校验开关
        String codeEnabled = basicDataService.getPhoneCodeEnabled();
        if ("admin".equals(form.getUsername()) || "false".equals(codeEnabled)) {
            userInfo = sysOutsideLoginService.login(form.getUsername(), passwordInfo);
        }
        // 获取用户为空，并且不是管理员，且手机校验开关开启走全部权限校验
        if (userInfo == null && !"admin".equals(form.getUsername()) && "true".equals(codeEnabled)) {
            userInfo = sysOutsideLoginService.login(form.getUsername(), passwordInfo, form.getPhonenumber(), form.getSmsCode());
        }
        if (userInfo == null) {
            return R.fail("无效登陆操作!");
        }
        // 获取登录token
        return R.ok(outsideTokenService.createToken(userInfo));
    }

}
